package com.zhuguowei.chapter_2_4.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.zhuguowei.chapter_2_4.utils.MyUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class TCPServerService extends Service {
    private static final String TAG = "TCPServerService";
    private boolean mIsServiceDestroyed = false;
    private String[] mDefinedMessages = new String[] {
            "你好啊，哈哈哈！",
            "请问你叫什么名字呀！",
            "今天深圳的天气好冷~~~",
            "你知道吗? 我可是可以和多个人同时聊天的哦。",
            "给你讲个笑话吧：据说爱笑的人运气都不会太差，不知道真假。"
    };

    public TCPServerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new TcpServer()).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mIsServiceDestroyed = true;
    }

    private class TcpServer implements Runnable {

        @Override
        public void run() {
            //创建Server对象 zgw-2017/12/5 15:48
            ServerSocket serverSocket = null;
            try {
                //监听本地8688端口 zgw-2017/12/5 15:51
                serverSocket = new ServerSocket(8688);
            } catch (IOException e) {
                Log.e(TAG, "establish tcp server failed,port:8688");
                e.printStackTrace();
            }

            //Service未销毁 zgw-2017/12/5 15:50
            while(!mIsServiceDestroyed) {
                //接收客户端请求 zgw-2017/12/5 15:52
                try {
                    final Socket client = serverSocket.accept();
                    Log.e(TAG, "run: accept 接收客户端请求");
                    //再次开启线程获取客户端的数据 zgw-2017/12/5 15:53
                    new Thread(){
                        @Override
                        public void run() {
                            try {
                                responseClient(client);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void responseClient(Socket client) throws IOException{
        //接收客户端消息 zgw-2017/12/5 16:01
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        //向客户端发送消息 zgw-2017/12/5 16:01
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
        out.println("欢迎来到聊天室！");
        //如果服务未销毁 zgw-2017/12/5 16:16
        while(!mIsServiceDestroyed) {
            //读取客户端发来的消息 zgw-2017/12/5 16:17
            String str = in.readLine();
            Log.e(TAG, "来自客户端的消息：" + str );
            if (str == null) {
                Log.e(TAG, "responseClient: 客户端断开连接");
                return;
            }
            int i = new Random().nextInt(mDefinedMessages.length);
            String msg = mDefinedMessages[i];
            out.println(msg);
            Log.e(TAG, "responseClient: 发往客户端的消息：" + msg);
        }
        Log.e(TAG, "responseClient: 客户端退出.");
        MyUtils.close(in);
        MyUtils.close(out);
        client.close();
    }
}
